package com.lysj.bhp.supernode.controller;


import com.lysj.bhp.manager.domain.Role;
import com.lysj.bhp.supernode.base.SuperNodeContent;
import com.lysj.bhp.supernode.domain.SuperNode;
import com.lysj.bhp.util.web.ParamUtil;
import com.lysj.bhp.util.web.Resp;
import com.lysj.bhp.util.web.SelectItem;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("admin/super_node")
public class SuperNodeController extends SuperNodeContent {

    @InitBinder
    public void InitBinder(WebDataBinder binder) {
        binder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd hh:mm"), true));
    }


    @GetMapping("/list")
    public Resp list(SuperNode model) {
        Specification specification = ParamUtil.createSpecification(model);
        List<SuperNode> superNodeList = superNodeRepository.findAll(specification, new Sort(Sort.Direction.DESC, "createDate"));
        return new Resp(superNodeList);
    }

    @PostMapping("/add")
    public Resp add(SuperNode model) {
        if (ParamUtil.isBlack(model.getName())) {
            return new Resp(Resp.PARAM_ERROR, "请输入节点名称");
        }
        if (ParamUtil.isBlack(model.getSuperNodeCode())) {
            return new Resp(Resp.PARAM_ERROR, "请输入节点编码");
        }
        SuperNode superNode = superNodeRepository.findBySuperNodeCode(model.getSuperNodeCode());
        if (!ParamUtil.isBlack(superNode)) {
            return new Resp(Resp.PARAM_ERROR, "节点编码已存在,请勿重复添加");
        }
        if (ParamUtil.isBlack(model.getRemark())) {
            return new Resp(Resp.PARAM_ERROR, "请输入备注");
        }
        model.setUserNumber(0); //下级用户数量默认为0
        model.setCreateDate(new Date());
        model.setCreateName(currentStaff().getRealname());
        superNodeRepository.save(model);
        return new Resp("添加成功");
    }

    @PostMapping("/remove")
    public Resp remove(SuperNode model) {
        return superNodeService.remove(model);
    }


    @GetMapping("select_item")
    public Resp selectItem() {
        List<SelectItem> selectItems = superNodeRepository.selectItems();
        return new Resp(selectItems);
    }

}
